from utils.DBUtils import DBUtils


class UserRegister:

    def __init__(self):
        self.__db_obj = DBUtils(host="localhost", port=3306, user='root', password='123456', database='test_123')

    def login(self):
        username = input("请输入用户名:")
        password = input("请输入密码:")
        result = self.__db_obj.fetch_one("select * from user where username=%s and password = %s", [username, password])
        if result and len(result) > 0:
            print('登录成功')
        else:
            print('账号或密码错误')

    def register(self):
        while True:
            username = input('请输入用户名：')
            result = self.__db_obj.fetch_one("select * from user where username=%s", [username])
            if result and len(result) > 0:
                print('用户名已被注册')
            else:
                break
        age = int(input('请输入年龄:'))
        while True:
            password = input('请输入密码:')
            re_password = input('请再次输入密码确认:')
            if password != re_password:
                print('两次密码不一致！')
            else:
                break

        try:
            self.__db_obj.execute("insert into user(username,age,password) values(%s,%s,%s)", [username, age, password])
        except Exception as e:
            print(e)
            return
        print('注册成功！')


if __name__ == "__main__":
    while True:
        print("""
            --------请选择用户注册或登录----------------------
            ---------01 注册    ----------------------
            ---------02 登录    ----------------------
            ---------03 退出    ----------------------
            -----------------------------------------
        """)
        register = UserRegister()
        num = int(input('1/2/3:'))
        if num == 1:
            register.register()
        elif num == 3:
            break
        else:
            register.login()


